//
//  HMStatusListViewModel.swift
//  微博
//
//  Created by 程双岐 on 16/9/23.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import YYModel
import SDWebImage


class HMStatusListViewModel: NSObject {
    
    lazy var statusList :[HMStadusViewModel] = [HMStadusViewModel]()

    func loadData(isPullup: Bool, callBack:@escaping (Bool,String)->()){
        let accessToken = HMUserAccpuntViewModel.sharedUserAccountViewModel.accessToken!
        
        var maxId: Int64 = 0
        
        var sinceId: Int64 = 0
        
        if isPullup {
            maxId = statusList.last?.status?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
        }else{
            sinceId = statusList.first?.status?.id ?? 0
        }
        
        var message:String = "没有加载到新数据"
        
        
        HMNetWorkTools.sharedTool.requserStatuses(accessToken: accessToken,sinceId: sinceId , maxId: maxId) { (response, error) in
            if error != nil{
                callBack(false,message)
                return
            }
            guard let dict = response as? [String : Any]else{
                print("你不是正确的字典格式")
                return
            }
            
            guard let statusArray = dict["statuses"] as? [[String : Any]] else{
                print("不是一个正确的字典数组")
                return
            }


            let arratList = NSArray.yy_modelArray(with: HMStatus.self, json: statusArray) as! [HMStatus]
            
            var tempArray = [HMStadusViewModel]()
            let group = DispatchGroup()
            
            for status in arratList{
                let viewModel = HMStadusViewModel(status: status)
                tempArray.append(viewModel)
                
                if status.pic_urls?.count == 1{
                    
                    if let url = status.pic_urls?.first?.thumbnail_pic{
                        
                        group.enter()
                        SDWebImageManager.shared().downloadImage(with: URL(string: url), options: [], progress: nil, completed: { (image, error, _, _, url) in
                            print("下载完成\(url)")
                            group.leave()
                        })
                        
                        
                        
                        
                    }
                    
                }
                if status.retweeted_status?.pic_urls?.count == 1{
                    if let url = status.retweeted_status?.pic_urls?.first?.thumbnail_pic{
                        

                        group.enter()
                        SDWebImageManager.shared().downloadImage(with: URL(string: url), options: [], progress: nil, completed: { (image, error, _, _, url) in
                            print("下载完成\(url)")
                            group.leave()
                        })
                        
                        
                        
                    }
                    

                }
            }
            
            group.notify(queue: DispatchQueue.main, execute: { 
                print("全部下载完成")
            })
            
//            self.statusList = tempArray
            
            if isPullup{
                self.statusList.append(contentsOf: tempArray)
            }else{
                self.statusList.insert(contentsOf: tempArray, at: 0)
            }
            
            if tempArray.count > 0{
                message = "加载了\(tempArray.count)跳微博数据"
            }
            
            
            //要想数据回调，前提单张图片全部下载完成，然后才能调用，要使用调度组这个技术，等待其他任务完成以后在调用
            callBack(true,message)
        }
        
    }

    
}
